package com.atguigu.yygh.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.config.MqConst;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.hosp.client.ScheduleFrignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.mq.RabbitMQService;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeiPatService;
import com.atguigu.yygh.order.utis.HttpRequestHelper;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author xin Zhou
 * @since 2024-02-05
 */
@Service
@Transactional
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private ScheduleFrignClient scheduleFrignClient;

    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private RabbitMQService rabbitMQService;

    @Autowired
    private WeiPatService weiPatService;

    @Autowired
    private PaymentService paymentService;

//    提交就诊人的信息
    @Override
    public Long submitOrder(String scheduleId, Long patientId) {
        //1 根据scheduleId获取排班数据
        ScheduleOrderVo scheduleOrderVo = scheduleFrignClient.getScheduleById(scheduleId);
        Date stopTime = scheduleOrderVo.getStopTime();
//        在超过当天挂号的截止时间
        if (new DateTime(stopTime).isBeforeNow()){
            throw new YyghException(20001,"超过当天挂号得到截止时间");
        }

        //2 根据patientId获取就诊人信息
        Patient patient = patientFeignClient.getPatientById(patientId);

        //3 平台里面 ==> 调用医院订单确认接口，
        // 3.1 如果医院返回失败，挂号失败
        //使用map集合封装需要传过医院数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",scheduleOrderVo.getHoscode());
        paramMap.put("depcode",scheduleOrderVo.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(scheduleOrderVo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", scheduleOrderVo.getReserveTime());
        paramMap.put("amount",scheduleOrderVo.getAmount()); //挂号费用
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        //String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", "");

        //使用httpclient发送请求，请求医院接口
        JSONObject result =
                HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");
        //根据医院接口返回状态码判断  200 成功
        if(result.getInteger("code") == 200) { //挂号成功
            // 3.2 如果返回成功，得到返回其他数据
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;

            //4 如果医院接口返回成功，添加上面三部分数据到数据库
            OrderInfo orderInfo = new OrderInfo();
            //设置添加数据--排班数据
            BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
            //设置添加数据--就诊人数据
            //订单号
            String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);
            orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
            orderInfo.setUserId(patient.getUserId());
            orderInfo.setPatientId(patientId);
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());

            //设置添加数据--医院接口返回数据
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);

            //调用方法添加
            baseMapper.insert(orderInfo);


//            5.更新平台上的可预约数(利用RabbitMq消息队列)
            OrderMqVo orderMqVo = new OrderMqVo();
//            获取可预约数和剩余可预约数
            int reservedNumber = result.getIntValue("reservedNumber");
            int availableNumber = result.getIntValue("availableNumber");
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setReservedNumber(reservedNumber);

            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(patient.getPhone());
            msmVo.setTemplateCode("您已经约约了上午${time}点的${name}医生的号,不要迟到!");
            HashMap<String, Object> msmMap = new HashMap<>();
            msmMap.put("time",scheduleOrderVo.getReserveDate()+" "+scheduleOrderVo.getReserveTime());
            msmMap.put("name","xxx");
            msmVo.setParam(msmMap);

            orderMqVo.setMsmVo(msmVo);
            rabbitMQService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);


            // 6 给就诊人发送短信

            // 7 返回订单号
            return orderInfo.getId();
        } else { //挂号失败
            throw new YyghException(20001,"挂号失败");
        }
    }

//    按条件的分页查询
    @Override
    public Page<OrderInfo> getOderInfoPage(Integer pageNum, Integer pageSize, OrderQueryVo orderQueryVo) {
        Page  page =new Page<>(pageNum,pageSize);
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

        Long userId = orderQueryVo.getUserId();             //用户Id
        String outTradeNo = orderQueryVo.getOutTradeNo();   //订单号
        String keyword = orderQueryVo.getKeyword();         //医院名称
        Long patientId = orderQueryVo.getPatientId();       //就诊人Id
        String orderStatus = orderQueryVo.getOrderStatus(); //订单信息
        String reserveDate = orderQueryVo.getReserveDate();
        String createTimeBegin = orderQueryVo.getCreateTimeBegin(); //下订单时间
        String createTimeEnd = orderQueryVo.getCreateTimeEnd(); //下订单的时间

        if (!StringUtils.isEmpty(userId)){
            queryWrapper.eq("user_id",userId);
        }
        if (!StringUtils.isEmpty(outTradeNo)){
            queryWrapper.eq("out_trade_no",outTradeNo);
        }
        if (!StringUtils.isEmpty(keyword)){
            queryWrapper.eq("hosname",keyword);
        }
        if (!StringUtils.isEmpty(patientId)){
            queryWrapper.like("patient_id",patientId);
        }
        if (!StringUtils.isEmpty(orderStatus)){
            queryWrapper.eq("order_status",orderStatus);
        }
        if (!StringUtils.isEmpty(reserveDate)){
            queryWrapper.ge("reserve_date",reserveDate);
        }
        if (!StringUtils.isEmpty(createTimeBegin)){
            queryWrapper.ge("create_time",createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)){
             queryWrapper.le("create_time",createTimeEnd);
        }
        Page<OrderInfo> page1 = baseMapper.selectPage(page, queryWrapper);
        page1.getRecords().parallelStream().forEach(item ->{
            this.packageOrderInfo(item);
        });
        return page1;
    }

    @Override
    public OrderInfo detail(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
//        更新剩余可预约数
        this.packageOrderInfo(orderInfo);
        return orderInfo;
    }

//    取消预约功能
    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
//        将Date类型转化为DateTime类型
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());

//        1.确定当前取消预约的时间 和 挂号订单取消预约的截止时间对比
        if (!quitTime.isBeforeNow()){
//          1.1当前时间是否已经超过了 挂号订单取消预约的截止时间 如果超过了直接抛出异常,不让用户取消
            throw new YyghException(20001,"超过了退号的截止时间");
        }
//        如果没超过,继续往下执行

        Map<String,Object> hopparamMap = new HashMap<>();
        hopparamMap.put("hoscode",orderInfo.getHoscode());
        hopparamMap.put("hosRecordId",orderInfo.getHosRecordId());
//        2.平台请求第三方医院,确定一下是否可以取消? 通知第三方医院,该用户已取消
        JSONObject jsonObject = HttpRequestHelper.sendRequest(hopparamMap, "http://localhost:9998/order/updateCancelStatus");
        if (jsonObject ==null || jsonObject.getIntValue("code") !=200){
//            2.1第三方医院不同意取消,抛出异常(不能取消)
            throw new YyghException(20001,"取消预约失败");
        }
//        3.判断用户是否对当前挂号订单是否已经支付
        if (orderInfo.getOrderStatus() == OrderStatusEnum.PAID.getStatus()){
//            3.1如果已经支付,则进行退款
           boolean flag = weiPatService.refund(orderId);
           if (!flag){
               throw  new YyghException(20001,"退款失败");
           }

        }
//            无论用户是否进行了支付进行下边的操作

//        4.更新订单的订单状态以及支付记录表的支付状态,改成已取消
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        baseMapper.updateById(orderInfo);

        UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderInfo.getId());
        updateWrapper.set("payment_status", PaymentStatusEnum.REFUND.getStatus());
        paymentService.update(updateWrapper);

//        5.更新医生的剩余可预约数
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        msmVo.setTemplateCode("xxxxx");
        msmVo.setParam(null);
        rabbitMQService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,msmVo);

//        6.给就诊人发送短信提示


    }

//    就医提醒
    @Override
    public void patientRemind() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.ne("order_status",-1);

//        查询到就诊人为今天的提示信息
        List<OrderInfo> orderInfos = baseMapper.selectList(queryWrapper);
        for (OrderInfo orderInfo : orderInfos) {
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitMQService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);
        }

    }

//    对订单表进行统计操作
    @Override
    public Map<String, Object> statistics(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> countVoList =  baseMapper.statistics(orderCountQueryVo);

        List<String> dateList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();
        for (OrderCountVo orderCountVo : countVoList) {
//            工作时间
            String reserveDate = orderCountVo.getReserveDate();
//            数量
            Integer count = orderCountVo.getCount();
            dateList.add(reserveDate);
            countList.add(count);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("dateList",dateList);
        map.put("countList",countList);
        return map;
    }

    private void packageOrderInfo(OrderInfo item) {
//        通过枚举类把订单状态信息转为文字
        String statusNameByStatus = OrderStatusEnum.getStatusNameByStatus(item.getOrderStatus());
        item.getParam().put("orderStatusString",statusNameByStatus);
    }



}
